<?php

namespace cf;

class Cookie
{
	///If expirePeriodMin=0, the cookie will expire at the end of the session (when the browser closes)
	
   function __construct($name, $expirePeriodMin=0, $path='/') 
   {
      $this->name = $name;
      $this->expMin = $expirePeriodMin;
      $this->path = $path;
      assert(!empty($this->name));
   }

	public function set() 
	{
		if (!setcookie(
					$this->name,
					"$this",
					$this->expMin ? (time() + $this->expMin * 60) : 0,
					$this->path) ) 
		{
			throw new Exception(
				"Cann't set cookie [$this->name]. Have there been any output before?"
			);
		}
		$_COOKIE[$this->name] = "$this";
	}

	static function retrieve($name) 
	{
		if (isset($_COOKIE[$name])) {
			$c = new Cookie($name);
			$c->params = unserialize($_COOKIE[$name]);
			return $c;
		}
		return false;
	}

   public function setExpirePeriod($min) 
   {
      $this->expMin = $min;
   }

   public function setParam($nm, $val) 
   {
      $this->params[$nm] = $val;
   }

   public function getParam($nm) 
   {
      if (!is_array($this->params) || !array_key_exists($nm,$this->params)) {
         return false;
	  }
      return $this->params[$nm];
   }
   
   public function delParam($nm) 
   {
       unset( $this->params[$nm] );
   }

   public function del() 
   {
      $saveExp = $this->expMin;
      $this->expMin = -17280000;
      $this->set();
      $this->expMin = $saveExp;
   }
   
   public function getParams() 
   {
      return $this->params;
   }

   public function __toString() 
   {
      return serialize($this->params);
   }

   private $name = '';
   private $expMin = 0;
   private $path = '/';
   private $params = array();
};

?>